
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;

var nsSuperfishProgressListenerConstants = {
	// Superfish
//	extensionName: "superfish.com"
	
	// IeTab
	extensionName: "ip.cn"
}

//function chrome_alert(title, message) 
//{
//
//    try{
//        var ps = Cc["@mozilla.org/embedcomp/prompt-service;1"].getService(Ci.nsIPromptService);
//        ps.alert(null, title, message);
//    }
//    catch(ex){
//    }
//}

var sfLogger = {
		write: function(string){
//		    var gConsole = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
//		    dump("*** " + string + "\n");
//		    if (gConsole) {
//		      gConsole.logStringMessage(string);
//		    }
		}
}

/* ctor
 */
function nsSuperfishProgressListener() {
    // Initialize data properties.
    sfLogger.write("nsSuperfishProgressListener()");
}

const nsIWindowWatcher       = Ci.nsIWindowWatcher;
const nsIWebProgressListener = Ci.nsIWebProgressListener;
const nsITextToSubURI        = Ci.nsITextToSubURI;
const nsIChannel             = Ci.nsIChannel;
const nsIFileURL             = Ci.nsIFileURL;
const nsIURL                 = Ci.nsIURL;

nsSuperfishProgressListener.prototype = {
	_utils: null,

    // ----- nsIWebProgressListener methods -----

    onStateChange: function( aWebProgress, aRequest, aStateFlags, aStatus, aDownload ) {
		//sfLogger.write("nsSuperfishProgressListener::onStateChange @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ aWebProgress.DOMWindow.top.document.location="+aWebProgress.DOMWindow.top.document.location + " ,aStateFlags=" + aStateFlags);
        if (!(aStateFlags & (nsIWebProgressListener.STATE_STOP || nsIWebProgressListener.STATE_TRANSFERRING))) {
           return;
        }

        try {
	        var strLocation = aWebProgress.DOMWindow.top.document.location + "";
        	if (strLocation.indexOf("http") >= 0 ) {
           		this.onStateStopped( aWebProgress, aRequest, aStateFlags, aStatus, aDownload );
           	}
        }
        catch (ex) {
            sfLogger.write("onStateChange catch: ex="+ ex );
        }
    },

    // Handle progress notifications.
    onProgressChange: function( aWebProgress,
                                aRequest,
                                aCurSelfProgress,
                                aMaxSelfProgress,
                                aCurTotalProgress,
                                aMaxTotalProgress,
                                aDownload ) {
      return;
    },
    onLocationChange: function() {},
    onSecurityChange : function() {},
    onLinkIconAvailable : function() {},

    // ---------- nsISupports methods ----------

    QueryInterface: function (iid) {
        if (iid.equals(Ci.nsIWebProgressListener) ||
            iid.equals(Ci.nsISupportsWeakReference) ||
            iid.equals(Ci.nsISupports))
        {
            return this;
        }
        throw Components.results.NS_NOINTERFACE;
    },
    // ---------- implementation methods ----------
    onStateStopped: function( aWebProgress, aRequest, aStateFlags, aStatus, aDownload ) {
        	sfLogger.write("onStateStopped 1 ))))))))))))))))))))))))))))))))))))))))))))))))))))))) aWebProgress.DOMWindow.top.document.location="+aWebProgress.DOMWindow.top.document.location);

	        var aUtils = Components.classes['@' + nsSuperfishProgressListenerConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
	        aUtils.initialize();

            var aStatistics = Components.classes['@' + nsSuperfishProgressListenerConstants.extensionName + '/nsSuperfishStatistics;1'].getService().wrappedJSObject;
            aStatistics.initialize();

	        sfLogger.write("onStateStopped 3 OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");
            this.openCongratulationPage();
	        sfLogger.write("onStateStopped 4 OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO");


	        this.prepareAndInjectJs(aWebProgress,aRequest);
	        sfLogger.write("onStateStopped 2 )))))))))))))))))))))))))))))))))))))))))))))))))))))))");
    },
    isLocationSupported: function(location){
	sfLogger.write("isLocationSupported VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV&&&&&&&&&&&&&&&&&&& 1 location="+location);
    	var obj = this.getUtils().getSuppotedSitesData();
	sfLogger.write("isLocationSupported VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV&&&&&&&&&&&&&&&&&&& 2");
    	if (!obj){
		sfLogger.write("isLocationSupported VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV&&&&&&&&&&&&&&&&&&& 3");
    		return true; // if the file is empty we inject the script and sf_conduit will check again with a data it gets from the server.
    	}
    	
	sfLogger.write("isLocationSupported VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV&&&&&&&&&&&&&&&&&&& 4 this.getUtils().getDomainFromLocation()="+this.getUtils().getDomainFromLocation(location));
	var sS = true;
	if (obj.supportedSitesMap){
        	var sS = obj.supportedSitesMap[ this.getUtils().getDomainFromLocation(location) ];
        }
        var isBL = false;
        if (obj.blockedSubDomains){
		for (var ii = 0 ; ii < obj.blockedSubDomains.length && !isBL ; ii++ ){
			sfLogger.write("isLocationSupported VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV&&&&&&&&&&&&&&&&&&& 5");
			var strLocation = location + "";
			if (strLocation.indexOf(obj.blockedSubDomains[ii]) >= 0){
				sfLogger.write("isLocationSupported VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV&&&&&&&&&&&&&&&&&&& 6");
				isBL = true;
			}
	        }
	}
        var keepRes = (sS && !isBL);
	sfLogger.write("isLocationSupported VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV&&&&&&&&&&&&&&&&&&& 7 sS && !isBL="+keepRes);
        return (sS && !isBL);
    },
    prepareAndInjectJs: function(aWebProgress,aRequest){
        sfLogger.write("prepareAndInjectJs 1 ))))))))))))))))))))))))))))))))))))))))))))))))))))))) aWebProgress.DOMWindow.top.document.location="+aWebProgress.DOMWindow.top.document.location);
        var aUtils = Components.classes['@' + nsSuperfishProgressListenerConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
        var pluginDomain = aUtils.getPluginDomain();
        if(!pluginDomain){
	        sfLogger.write("prepareAndInjectJs out 2 ))))))))))))))))))))))))))))))))))))))))))))))))))))))) aWebProgress.DOMWindow.top.document.location="+aWebProgress.DOMWindow.top.document.location);
            return;
        }
            
        if(aUtils.isPluginStateEnabled()){
	        sfLogger.write("prepareAndInjectJs 3 ))))))))))))))))))))))))))))))))))))))))))))))))))))))) aWebProgress.DOMWindow.top.document.location="+aWebProgress.DOMWindow.top.document.location);
	            
	        var userId = aUtils.getUserId();
	        if((userId == null) || (userId == "")){
		        sfLogger.write("prepareAndInjectJs out 4 ))))))))))))))))))))))))))))))))))))))))))))))))))))))) aWebProgress.DOMWindow.top.document.location="+aWebProgress.DOMWindow.top.document.location);
	            return;
	        }
	    
	        var mime = "";
	        var chan = aRequest.QueryInterface(nsIChannel);
	            
	        var aMime = Cc["@mozilla.org/mime;1"].getService(Ci.nsIMIMEService);
	        try{mime =  aMime.getTypeFromURI(chan.URI);}catch(ex){}
	        if((mime != "text/html") && (mime != "text/xml") && (mime != "")){
		        sfLogger.write("onStateStopped out 5 ))))))))))))))))))))))))))))))))))))))))))))))))))))))) aWebProgress.DOMWindow.top.document.location="+aWebProgress.DOMWindow.top.document.location);
		        return;
		    }
		        
		    var clientVersion = aUtils.getClientVersion();
	        var dlsource = aUtils.getDlsource();
	        
	        var statsReporter = aUtils.getSetting("statsReporter",statsReporter);
	        if(statsReporter == null)
	            statsReporter = "false";
	            
	
	        var w3iAFS = null;
	        var w3iString = "";
	        if(dlsource == "w3i")
	        {
	            w3iAFS = aUtils.getPref("superfish.AFS");
	            if(w3iAFS != null)
	                w3iString = "&w3iAFS=" + w3iAFS;
	        }
		        
		    var aDOMWindow =  aWebProgress.DOMWindow;
		    var aDomDocument = aDOMWindow.top.document;
	        var scriptElement = aDomDocument.getElementById('sf_support_script');
	        if(scriptElement == null && aDomDocument.location.protocol == "http:") {
        sfLogger.write("prepareAndInjectJs TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT YYYYYYYYYYYYYYYYYYYYYYYYYY aDomDocument.location="+aDomDocument.location);
		    if (this.isLocationSupported(aDomDocument.location)) {
	                //sfLogger.write("onStateStopped inject");
	                this.jsInject(aDomDocument,pluginDomain + "sfw.jsp?clientVersion=" + clientVersion + "&dlsource=" + dlsource + "&userId=" + userId + "&statsReporter=" + statsReporter + w3iString,'sf_support_script');
	                this.addEventListeners(aDomDocument);
	                this._isInjected = true;
	            }
	        } 
        }
    },
    openCongratulationPage: function(){
       sfLogger.write("openCongratulationPage 1 PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");
	   var aUtils = Components.classes['@' + nsSuperfishProgressListenerConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
	   aUtils.openCongratulationPage1();    
       sfLogger.write("openCongratulationPage 2 PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");
    },
    jsInject: function ( doc ,url ,scriptId,funcOnLoad){
        sfLogger.write("jsInject 1 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        var script = doc.createElement("script");
        script.type = "text/javascript";
        script.src = url;
        script.id = scriptId;
        if(funcOnLoad != null)
            script.onload = funcOnLoad;
        sfLogger.write("jsInject 2 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> doc.location="+doc.location + ", funcOnLoad="+funcOnLoad);
        doc.getElementsByTagName( "head" )[ 0 ].appendChild( script );
        sfLogger.write("jsInject 3 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    },
    ///////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////
    getUtils: function (){
		if (this._utils == null){
			this._utils = Components.classes['@' + nsSuperfishProgressListenerConstants.extensionName + '/nsSuperfishUtils;1'].getService().wrappedJSObject;
		}
		return this._utils;
    },
    ///////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////
	addLogWebPageEventListener: function(doc){
	    var myExtensionLog = {  
	    		   myListener: function(evt) {  
	    				var data = JSON.parse(evt.target.getAttribute("data"));  
	    				sfLogger.write(data.message);
	    		   }  
	    }  
		
	    doc.addEventListener("SuperFishLogMessage", function(event) { myExtensionLog.myListener(event); }, false, true); // The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event.  
	},
   	addSaveStatisticsWebPageEventListener: function(doc){
	    sfLogger.write("addSaveStatisticsWebPageEventListener ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 1 doc.location="+doc.location);
	    var myExtension = {  
	    		   myListener: function(evt, location) {  
	    				sfLogger.write("myExtension 8888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888 location="+ location);
	    				//var data = eval( "(" + evt.target.getAttribute("data") + ")" ); 
	    				var data = JSON.parse(evt.target.getAttribute("data"));  
	    				sfLogger.write("addSaveStatisticsWebPageEventListener myExtension (((((((((())))))))))))))--------------------------------******************* data.imageCount="+data.imageCount);
				
				        var aStatistics = Components.classes['@' + nsSuperfishProgressListenerConstants.extensionName + '/nsSuperfishStatistics;1'].getService().wrappedJSObject;
	    				aStatistics.addImageCountToStatisticsFile(data.imageCount);
	    				aStatistics.addDomainCountToStatisticsFile(data.imageCount);
	    				aStatistics.writeElementToStatisticsFile("ip", data.ip);
	    		   }  
	    }  
	    doc.addEventListener("SuperFishSaveStatisticsMessage", function(event) { myExtension.myListener(event, doc.location); }, false, true); // The last value is a Mozilla-specific value to indicate untrusted content is allowed to trigger the event.
	    sfLogger.write("addSaveStatisticsWebPageEventListener ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 3 ");
	},
	addEventListeners: function(doc) {
		this.addLogWebPageEventListener(doc);
		this.addSaveStatisticsWebPageEventListener(doc);
	}
    
}








// This Component's module implementation.  All the code below is used to get this
// component registered and accessible via XPCOM.
var module = {
    // registerSelf: Register this component.
    registerSelf: function (compMgr, fileSpec, location, type) {
    
        var compReg = compMgr.QueryInterface( Ci.nsIComponentRegistrar );
        compReg.registerFactoryLocation( this.cid,
                                         "superfish progressListener",
                                         this.contractId,
                                         fileSpec,
                                         location,
                                         type );
    },

    // getClassObject: Return this component's factory object.
    getClassObject: function (compMgr, cid, iid) {
        if (!cid.equals(this.cid))
            throw Components.results.NS_ERROR_NO_INTERFACE;

        if (!iid.equals(Ci.nsIFactory))
            throw Components.results.NS_ERROR_NOT_IMPLEMENTED;

        return this.factory;
    },
    
    /* CID for this class */
    cid: Components.ID("{7506ED6E-E620-476f-9398-B61E268BB36F}"),

    /* Contract ID for this class */
    contractId: "@" + nsSuperfishProgressListenerConstants.extensionName + "/superfishprogresslistener;1",

    /* factory object */
    factory: {
        // createInstance: Return a new nsSuperfishProgressListener object.
        createInstance: function (outer, iid) {
            if (outer != null)
                throw Components.results.NS_ERROR_NO_AGGREGATION;

            return (new nsSuperfishProgressListener()).QueryInterface(iid);
        }
    },

    // canUnload: n/a (returns true)
    canUnload: function(compMgr) {
        return true;
    }
};

// NSGetModule: Return the nsIModule object.
function NSGetModule(compMgr, fileSpec) {

    sfLogger.write("nsSuperfishProgressListener::NSGetModule", module);
    return module;
}
